#coding=utf-8
import time
from selenium import webdriver
from appium import webdriver
from Tool.usefulTools import userfulToolsFactory
import sys
from time import sleep
import TestCase

el_not_find = '控件未找到，控件名称：'

class Base():
    driver = None
    desired_caps = {}
    desired_caps['platformName'] = 'Android'
    # desired_caps['platformVersion'] = '4.3'
    # desired_caps['deviceName'] = '50a4c97e'
    desired_caps['platformVersion'] = '6.0'
    desired_caps['deviceName'] = '10463120'
    # desired_caps['platformVersion'] = '5.1'
    # desired_caps['deviceName'] = 'A10SBNGTQJ9M'
    desired_caps['appPackage'] = 'cn.com.egova.egovamobile'
    desired_caps['appActivity'] = '.login.LoginActivity'
    desired_caps['unicodeKeyboard'] = True
    desired_caps['resetKeyboard'] = True

    driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
    # driver.find_element().is_displayed()

class switch(object):
    def __init__(self, value):
        self.value = value
        self.fall = False

    def __iter__(self):
        """Return the match method once, then stop"""
        yield self.match
        raise StopIteration

    def match(self, *args):
        """Indicate whether or not to enter a case suite"""
        if self.fall or not args:
            return True
        elif self.value in args:  # changed for v1.5, see below
            # self.fall = True
            return True
        else:
            return False


class BasicAction():
    def find_element(self,locate,file_path):
        file_name = locate[0] + '-获取失败'
        file = file_path + '//'+file_name.decode("utf-8") + '.png'
        for case in switch(locate[1]):
            if case('id'):
                print "find_method = " + locate[2]
                try:
                    element = Base.driver.find_element_by_id(str(locate[2]))
                    print locate[0].decode("utf-8") + '-控件--已找到，查找方式：id'.decode("utf-8")
                except Exception,e:
                    print e
                    print el_not_find.decode("utf-8") + locate[0].decode("utf-8")
                    Base.driver.get_screenshot_as_file(file)
                    raise

            if case('name'):
                try:
                    element = Base.driver.find_element_by_name(locate[2])
                    print locate[0].decode("utf-8") + '-控件-- 已找到，查找方式：NAME'.decode("utf-8")
                except Exception,e:
                    print e
                    print el_not_find.decode("utf-8") + locate[0].decode("utf-8")
                    Base.driver.get_screenshot_as_file(file)
                    raise

            if case('class_name'):
                try:
                    element = Base.driver.find_element_by_class_name(locate[2])
                    print locate[0].decode("utf-8") + '-控件-- 已找到，查找方式：class_name'.decode("utf-8")
                except Exception,e:
                    print e
                    print el_not_find.decode("utf-8") + locate[0].decode("utf-8")
                    Base.driver.get_screenshot_as_file(file)
                    raise

            if case('xpath'):
                try:
                    element = Base.driver.find_element_by_xpath(locate[2])
                    print locate[0].decode("utf-8") + '-控件-- 已找到，查找方式：xpath'.decode("utf-8")
                except Exception, e:
                    print e
                    print el_not_find.decode("utf-8") + locate[0].decode("utf-8")
                    Base.driver.get_screenshot_as_file(file)
                    raise

            return element

basicAction = BasicAction()

class element_Oprate():

    def element_click(self,locate,file_path):
        try:
            element = basicAction.find_element(locate,file_path)
            element.click()
            sleep(2)
        except Exception,error:
            print error
            print '点击操作失败,控件名称：'.decode("utf-8") + locate[0].decode("utf-8")
            raise

    def elemet_clear(self,locate,file_path):
        try:
            element = basicAction.find_element(locate,file_path)
            element.clear()
            sleep(2)
        except Exception,error:
            print error
            print '清空操作失败,控件名称：'.decode("utf-8") + locate[0].decode("utf-8")

    def element_send_keys(self,locate,context,file_path):
        try:
            self.locate = locate
            element = basicAction.find_element(self.locate,file_path)
            element.clear()
            element.send_keys(context.decode("utf-8"))
            sleep(2)
        except Exception,error:
            print error
            print '输入内容失败,控件名称：'.decode("utf-8") + locate[0].decode("utf-8")

    def element_display_commit(self,locate,file_path):
        try:
            self.locate = locate
            element = basicAction.find_element(self.locate,file_path)
            element.is_displayed()
            return True
        except Exception, error:
            return False
            # print error
            # print '检查的控件未找到,控件名称：'.decode("utf-8") + locate[0].decode("utf-8")
            raise

    def element_save_pic(self,file_path,file_name):
        file = file_path + '//'+ file_name.decode("utf-8") + '.png'
        Base.driver.get_screenshot_as_file(file)

    def set_pic_path(self):
        userfulTool = userfulToolsFactory()
        base_dir = sys.path[0] + '/'
        relative_address = userfulToolsFactory.creat_dir(userfulTool, base_dir)
        pic_file_path = base_dir + '//' + relative_address
        return pic_file_path


def test():
    return 0

if __name__ == '__main__':
    # base = Base()
    test = ['登录输入框','id',"cn.com.egova.egovamobile:id/login_txtUsername"]
    baseFunction = Base()
    print  test[2]
    # el = baseFunction.find_element(test)
    # el.clear()
    # baseFunction.element_send_keys(test,'test')
    # baseFunction.element_save_pic('d:/','测试')